package br.edu.unicentro.mymib.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.edu.unicentro.mymib.base.EMFactory;

@Entity
@NamedQueries( { @NamedQuery(name = "tag.findByName", query = "from Tag as t where t.nome = :tagName") })
public final class Tag {

	@Id
	@GeneratedValue
	private Long id;
	
	@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "tags", targetEntity = Post.class)
	private List<Post> posts;
	
	@Column
	private String nome;

	public Tag() {
	}

	public Long getId() {
		return id;
	}

	public Tag(String nome) {
		this.nome = nome;
	}

	public String getNome() {
		return nome;
	}

	public List<Post> getPosts() {
		return posts;
	}
	
	public static Tag buscarPorNome(String tagName) {
		EntityManager em = EMFactory.getManager();
		Query query = em.createNamedQuery("tag.findByName");
		query.setParameter("tagName", tagName);
		try {
			return (Tag) query.getSingleResult();
		} catch (NoResultException e) {
			Tag tag = new Tag(tagName);
			return tag;
		}
	}

}
